<template>
    <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <div class="recommend-list">
            <div class="recommend-list-item" v-for="prod in recommendList" :key="prod.id" @click="handleItemClick(prod)">
                <img :src="prod.image" alt="">
                <div class="title van-multi-ellipsis--l2">{{ prod.title }}</div>
                <div class="price van-multi-ellipsis--l2">
                    <slot name="price" :price="prod.price">
                        <span>{{ money(prod.price) }}</span>
                    </slot>
                    <slot name="originprice">
                        <span>原价: {{ money(prod.originPrice) }}</span>
                    </slot>
                </div>
            </div>
        </div>
    </van-list>
</template>

<script lang="ts" setup>
import { ref, useAttrs } from 'vue';
import { useRoute } from 'vue-router';

const route = useRoute()

// 推荐商品列表
const recommendList = ref<Product[]>([])

const attrs = useAttrs()


/**
 * 属性定义
 */
// 接收父组件传来的方法(父传子)
const props = defineProps<{
    requestApi: any //请求接口数据的方法
    [prop: string]: any // 额外的其它的属性
}>()

// 向父组件传递数据(子传父)
const emit = defineEmits(['click-item'])



/**
 * 触底加载更多数据
 */
const count = ref<number>(1)
const loading = ref<boolean>(false)
const finished = ref<boolean>(false)


// 格式化金额数字，小数点后显示两位小数
const money = (val: string | number) => {
    return Number(val).toFixed(2)
}

// 加载更多数据
const onLoad = async () => {
    console.log('正在加载...');
    const {
        requestApi,
    } = props


    try {
        // 查询更多数据
        const result = await requestApi(route.query.id, count.value, attrs)
        // 将查询出的更多数据与原推荐商品数据合并
        recommendList.value = recommendList.value.concat(result.list)
        console.log('result>>>>>:', result)

        // 更新页码值
        count.value += 10
        // 处理完毕，手动将 loading 置为 false
        loading.value = false
        // 如果没有更多数据，则将 finished 置为 true
        finished.value = result.length === 0
    } catch (error) {
        console.log('查询数据异常:', error)

        //  出现异常，重置 loading 与 finished
        loading.value = false
        finished.value = true
    }

}

// 点击列表每一项时，触发事件抛出数据
const handleItemClick = (prod: Product) => {
    // 触发一个事件，向父组件抛出数据
    // 父组件拿到数据后，跳转到detail
    emit('click-item', prod)
}

</script>

<style lang="less" scoped>

// 推荐商品
.recommend-list {
    width: 375px;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    // .recommend-list-item
    &-item {
        width: 180px;
        height: 180px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        align-items: center;

        img {
            width: 160px;
            height: 120px;
        }
    }
}
</style>
